package hoge.memoriesalbum.post;

import hoge.memoriesalbum.util.Log;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * GAE側にPOSTする
 * 
 * @author hyoromo
 */
class PostData {
    static final String POST_URL = "http://photo-storage.appspot.com/upload";

    public boolean post(String imageUrl) {
        // POSTするための準備
        HttpURLConnection con;
        try {
            URL url = new URL(POST_URL);
            con = (HttpURLConnection) url.openConnection();

            // タイプの指定
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setRequestProperty("Accept-Language", "multipart/form-data");

            // byteで受けられるように指定(GAE側で判断が入ってる)
            con.setRequestProperty("X-RAW", "true");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        // POST可能データに変換する
        InputStream is = null;
        try {
            is = new FileInputStream(imageUrl);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // POSTする
        OutputStream os = null;
        int c;
        try {
            os = con.getOutputStream();
            while ((c = is.read()) != -1) {
                os.write(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // POST結果を受け取る
        is = null;
        BufferedReader reader;
        try {
            is = con.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is));
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            try {
                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return false;
        }

        // POST結果を出力
        String s;
        try {
            while ((s = reader.readLine()) != null) {
                Log.v(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}